<?php
class DataHandler {
	private static $iLevel = 0;
	private static $oDB;

	public static function connect($sDataHost, $sDataBase, $sDataUser, $sDataPass) {
		$sConnectionString = 'mysql:host='.$sDataHost;
		if (strlen($sDataBase) > 0) {
			$sConnectionString .= ';dbname='.$sDataBase;
		}
		DataHandler::$oDB = new PDO($sConnectionString, $sDataUser, $sDataPass);
		DataHandler::$oDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}
	
	public static function beginTransaction() {
		if (DataHandler::$iLevel == 0) {
			DataHandler::$oDB->beginTransaction();
		}
		else {
			DataHandler::$oDB->exec("SAVEPOINT LEVEL{DataHandler::$transLevel}");
		}

		DataHandler::$iLevel++;
	}
	
	public static function commit() {
		DataHandler::$iLevel--;

		if (DataHandler::$iLevel == 0) {
			DataHandler::$oDB->commit();
		}
		else {
			DataHandler::$oDB->exec("RELEASE SAVEPOINT LEVEL{DataHandler::$transLevel}");
		}
	}

	public static function rollback() {
		DataHandler::$iLevel--;

		if (DataHandler::$iLevel == 0) {
			DataHandler::$oDB->rollback();
		}
		else {
			DataHandler::$oDB->exec("ROLLBACK TO SAVEPOINT LEVEL{DataHandler::$transLevel}");
		}
	}
	
	public static function lastInsertId() {
		return DataHandler::$oDB->lastInsertId();
	}
	
	public static function prepare($sQuery) {
		return DataHandler::$oDB->prepare($sQuery);
	}
	
	public static function query($sQuery) {

		$arrParams = func_get_args();
		array_shift($arrParams);

		$oQuery = DataHandler::$oDB->prepare($sQuery);
		$oQuery->execute($arrParams);

		return $oQuery;
	}
}
?>
